﻿using System.Web.Mvc;

namespace CodeContrib.Web.Mvc.Html
{
	public static class LinkExtensions
	{
		public static MvcHtmlString Link(this HtmlHelper htmlHelper, MvcHtmlString innerHtml, string url)
		{
			return Link(htmlHelper, innerHtml.ToHtmlString(), url, null);
		}

		public static MvcHtmlString Link(this HtmlHelper htmlHelper, string innerHtml, string url)
		{
			return Link(htmlHelper, innerHtml, url, null);
		}

		public static MvcHtmlString Link(this HtmlHelper htmlHelper, MvcHtmlString innerHtml, string url, object htmlAttributes)
		{
			return Link(htmlHelper, innerHtml.ToHtmlString(), url, htmlAttributes);
		}

		public static MvcHtmlString Link(this HtmlHelper htmlHelper, string innerHtml, string url, object htmlAttributes)
		{
			if (string.IsNullOrEmpty(url))
			{
				return MvcHtmlString.Create(innerHtml);
			}

			var link = new TagBuilder("a")
				           {
					           InnerHtml = innerHtml
				           };
			link.Attributes["title"] = url;

			var attributes = htmlAttributes.ToHtmlAttributes();

			foreach (var attribute in attributes)
			{
				var value = attribute.Value.ToString();

				if (!string.IsNullOrEmpty(value))
				{
					link.Attributes[attribute.Key] = value;
				}
			}

			link.Attributes["href"] = url;

			return MvcHtmlString.Create(link.ToString());
		}
	}
}